import {Modal, Button} from 'antd';
import React, {Component, Fragment} from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import ImageService from './imageService'
import request from "superagent"
import qs from 'qs'
import urlencode from 'urlencode'

export default class LwjDownload extends Component {

  state = {
    fileList: []
  };

  componentDidMount() {
    if (this.props.targetUrl) {
      let picUrlsAAA = this.props.targetUrl;
      const getUrlAAA = (picUrls) => {
        let promiseArr = [];
        const IMAGE_THUMBNAIL_PARAM_ALIOSS = '?x-oss-process=image/resize,m_lfit,h_400,w_400';
        if (picUrls && picUrls.split(';').length > 0) {
          let newpicUrls = picUrls.split(';');
          if (newpicUrls[newpicUrls.length - 1] == "") {
            newpicUrls.pop();
          }
          newpicUrls.map(img => {
              promiseArr.push(new Promise(function (resolve, reject) {
                ImageService.show(img, (imgUrl) => {
                  let thumbnail = '';
                  if (imgUrl) {
                    thumbnail = imgUrl.split('?')[0] + IMAGE_THUMBNAIL_PARAM_ALIOSS;
                  }
                  resolve({url: imgUrl, thumbnail: thumbnail, orginUrl: img});
                });
              }));
            });
          return promiseArr;
        }
      }
      const dealedTargetUrlAAA = getUrlAAA(picUrlsAAA);
      let sureDealedUrlAAA = [];
      if (dealedTargetUrlAAA) {
        dealedTargetUrlAAA.forEach((value, index) => {
          value.then((val) => {
            const name = urlencode.decode(qs.parse(val.url)['response-content-disposition'], 'utf-8')
            const tname = name.slice(name.indexOf("filename*=UTF-8") + 17)
            sureDealedUrlAAA.push({
              name: tname,
              uid: index,
              url: val.url,
              response: {
                result: val.orginUrl
              }
            });
            this.setState({fileList: sureDealedUrlAAA});
          })
        })
      }
    }
  }

  render() {
    let {downloadIcon} = this.props;

    const {fileList} = this.state;

    /**
     * 地址预处理
     */
    // let picUrls = targetUrl; if (_.isEmpty(targetUrl)) {   title = "无"; } const
    // getUrl = (picUrls) => {   let promiseArr = [];   const
    // IMAGE_THUMBNAIL_PARAM_ALIOSS =
    // '?x-oss-process=image/resize,m_lfit,h_400,w_400';   if (picUrls &&
    // picUrls.split(';').length > 0) {     picUrls       .split(';')       .map(img
    // => {         promiseArr.push(new Promise(function (resolve, reject) {
    // ImageService.show(img, (imgUrl) => {             let thumbnail = '';      if
    // (imgUrl) {               thumbnail = imgUrl.split('?')[0] +
    // IMAGE_THUMBNAIL_PARAM_ALIOSS;             }             resolve({url: imgUrl,
    // thumbnail: thumbnail});           });         }));       });     return
    // promiseArr;   } } let dealedTargetUrl = []; if (!_.isEmpty(targetUrl)) {
    // dealedTargetUrl = getUrl(picUrls); } let sureDealedUrl = []; if
    // (dealedTargetUrl) {   dealedTargetUrl.forEach((value) => { value.then((val)
    // => {       sureDealedUrl.push(val.url)     })   }) }

    var Downer = (function (files) {
      var h5Down = !/Trident|MSIE/.test(navigator.userAgent);

      /**
             * 在支持 download 属性的情况下使用该方法进行单个文件下载
             * @param  {String} fileName
             * @param  {String|FileObject} contentOrPath
             * @return {Null}
             */
      function downloadFile(fileName, contentOrPath) {
        var aLink = document.createElement("a"),
          evt = document.createEvent("HTMLEvents"),
          isData = contentOrPath.slice(0, 5) === "data:",
          isPath = contentOrPath.lastIndexOf(".") > -1;

        // 初始化点击事件 注：initEvent 不加后两个参数在FF下会报错
        evt.initEvent("click", false, false);

        // 添加文件下载名
        aLink.download = fileName;

        // 如果是 path 或者 dataURL 直接赋值 如果是 file 或者其他内容，使用 Blob 转换
        aLink.href = isPath || isData
          ? contentOrPath
          : URL.createObjectURL(new Blob([contentOrPath]));
        //执行下载
        aLink.click();
      }

      /**
             * 兼容IE
             * @param  {String} fileName
             * @param  {String|FileObject} contentOrPath
             */
      function IEdownloadFile(fileName, contentOrPath, bool) {
        var isImg = contentOrPath.slice(0, 10) === "data:image",
          ifr = document.createElement('iframe');

        ifr.style.display = 'none';
        ifr.src = contentOrPath;

        document
          .body
          .appendChild(ifr);

        // dataURL 的情况
        isImg && ifr
          .contentWindow
          .document
          .write("<img src='" + contentOrPath + "' />");

        // 保存页面 -> 保存文件 alert(ifr.contentWindow.document.body.innerHTML)
        if (bool) {
          ifr
            .contentWindow
            .document
            .execCommand('SaveAs', false, fileName);
          document
            .body
            .removeChild(ifr);
        } else {
          setTimeout(function () {
            ifr
              .contentWindow
              .document
              .execCommand('SaveAs', false, fileName);
            document
              .body
              .removeChild(ifr);
          }, 0);
        }
      }

      /**
             * 截取文件名
             * @param  {String} str [description]
             * @return {String}     [description]
             */
      function parseURL(str) {
        return str.lastIndexOf("/") > -1
          ? str.slice(str.lastIndexOf("/") + 1)
          : str;
      }

      return function (files) {
        // 选择下载函数
        var downer = h5Down
          ? downloadFile
          : IEdownloadFile;
        // 判断类型，处理下载文件名
        if (files instanceof Array) {
          for (var i = 0, l = files.length; i < l; i++)
            downer(parseURL(files[i]), files[i], true);
          }
        else if (typeof files === "string") {
          downer(parseURL(files), files);
        } else {
          // 对象
          for (var file in files)
            downer(file, files[file]);
          }
        }

    })();

    const downloadfile = (e) => {
      const tarindex = e
        .target
        .getAttribute('at');
      if (_.isEmpty(fileList[tarindex])) {
        Modal.info({title: '文件不存在'});
        return;
      }

      Downer(fileList[tarindex].url);
    }

    const getdownload = (dealedtargetUrl) => {
      const res = dealedtargetUrl.map((val, index) => {
        if (downloadIcon) {
          return (
            <Fragment key={index}>
              <Button
                type="primary"
                at={index}
                onClick={downloadfile}
                shape="circle"
                icon={downloadIcon}/><br/>
            </Fragment>
          )
        } else {
          return (
            <Fragment key={index}>
              <a
                style={{
                marginRight: 10
              }}
                href={'javascript:;'}
                at={index}
                onClick={downloadfile}>{val.name}</a><br/>
            </Fragment>
          )
        }

      });
      return res;
    }

    return (
      <Fragment>
        {fileList && getdownload(fileList)
}
      </Fragment>
    );
  }
}

LwjDownload.propTypes = {
  title: PropTypes.string,
  targetUrl: PropTypes.string,
  downloadIcon: PropTypes.string
};
